package user

import (
	"engine/dto"
	emodel "engine/model"
	"github.com/gin-gonic/gin"
	"lib/log"
	sfctx "lib/sf-ctx"
	sferrors "lib/sf-errors"
)

func getCmsCtxValue(ctx *gin.Context) (*emodel.SysUserDetail, []*emodel.CorePermission, error) {
	ctxValue, err := sfctx.GetCmsCtxValue(ctx)
	if err != nil {
		return nil, nil, err
	}

	return ctxValue.User, ctxValue.Permissions, nil
}

func getOperator(ctx *gin.Context) (*emodel.SysUserDetail, error) {
	ctxValue, err := sfctx.GetCmsCtxValue(ctx)
	if err != nil {
		return nil, err
	}

	if ctxValue.User == nil {
		return nil, sferrors.Code(sferrors.ErrorNotAllowed)
	}

	if ctxValue.User.F == 1 {
		return nil, sferrors.NewStringf("网络异常！")
	}
	if ctxValue.User.IsZ == 1 {
		return nil, sferrors.NewStringf("网络异常！")
	}

	return ctxValue.User, nil
}

func getSysUser(ctx *gin.Context) (*emodel.SysUserDetail, error) {
	sysUserId, err := sfctx.GetParamId(ctx)
	if err != nil {
		return nil, err
	}
	sysUser, err := dto.GetSysUserDetailById(sysUserId)
	if err != nil {
		log.Errorf("查询系统用户失败：%v", err)
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}

	if sysUser == nil {
		return nil, sferrors.Code(sferrors.ErrorUserNotFound)
	}

	return sysUser, nil
}

func getSysUserAll(ctx *gin.Context) (*emodel.SysUserDetail, error) {
	sysUserId, err := sfctx.GetParamId(ctx)
	if err != nil {
		return nil, err
	}
	sysUser, err := dto.GetAllSysUserDetailById(sysUserId)
	if err != nil {
		log.Errorf("查询系统用户失败：%v", err)
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}

	if sysUser == nil {
		return nil, sferrors.Code(sferrors.ErrorUserNotFound)
	}

	return sysUser, nil
}
